package com.solidsnake.scala.service

import java.nio.charset.Charset
import com.solidsnake.scala.http.{HttpHandlerField, HttpUtils}
import java.io.{File, FileOutputStream}
import com.solidsnake.scala.image.CalculateImageDataManager
import java.net.URLEncoder

/**
 * Created with IntelliJ IDEA.
 * User: solidsnake
 * Date: 13-11-22
 * Time: 下午2:29
 * To change this template use File | Settings | File Templates.
 */
object LoginService {

  /**
     *   需要的参数， IP可以伪造
     * @param ip
     * @param url
     * @return
     */
  def requestMainPage(ip : String, url : String) = {
    val requestHandler = Map[String, String]()
    val params = Map("hfIp" -> ip)
    HttpUtils.postText(url, params, Charset.forName("UTF-8"), requestHandler, true)
  }



  def submitLoginInfo(url : String, vc : String,validateV : String, cookie : String)(userName : String, password : String) = {
    val requestHandler = Map(HttpHandlerField.REFERER -> "http://app02.szaic.gov.cn/WERMIS2.WebUI/Default.aspx", HttpHandlerField.COOKIE -> cookie)
    val loginParams = Map("smObj" -> "Login1$UpdatePanel2|Login1$ibtnLoginEnter",
      "__EVENTTARGET" -> "",
      "__EVENTARGUMENT" -> "",
      "__VIEWSTATE" -> URLEncoder.encode(validateV),
      "Login1$txtUserID" -> userName,
      "Login1$txtPassword" -> password,
      "Login1$txtCheckCode" -> vc,
      "Login1$hfPublicKeyExponent" -> "",
      "Login1$hfPublicKeyModulus" -> "",
      "Login1$ibtnLoginEnter.x" -> "30",
      "Login1$ibtnLoginEnter.y" ->"9")
    HttpUtils.postText(url, loginParams, Charset.forName("UTF-8"), requestHandler, true)
  }

  /**
   *  查看登录状态
   * @param url
   * @param cookie
   * @return
   */
  def checkLoginStatus(url : String, cookie : String) : Boolean = {
    val requestHandler = Map(HttpHandlerField.COOKIE -> cookie)
    val loginStatusResult = HttpUtils.getText(url, Map(), Charset.forName("UTF-8"), requestHandler, false)
    return loginStatusResult._3.indexOf("欢迎您") != -1
  }

  /**
   * 用户登录
   * @param userName 用户名
   * @param password 密码
   * @return
   */
  def login(userName : String, password : String) : ClientParams = {

    // 请求主页面信息
    val mainUrl = "http://app02.szaic.gov.cn/WERMIS2.WebUI/Default.aspx"
    val clientCookie = new ClientParams()
    val result = this.requestMainPage("192.168.0.198", mainUrl)
    clientCookie.loadCookie(result._1, result._2)

    // 请求验证码信息
    val validateUrl = ValidateCodeService.getLoginValidateUrl(result _3)
    val validateResult = ValidateCodeService.requestLoginValidateCode(validateUrl _1, validateUrl _2, clientCookie.cookie)
    // 计算验证码
    val vc = ValidateCodeService.calculateValidateCodeDate(validateResult._3)
    clientCookie.loadCookie(validateResult._1, validateResult._2)
    clientCookie.loadViewState(result _3)

    // 提交登录信息
    val submitLoginResult = this.submitLoginInfo("http://app02.szaic.gov.cn/WERMIS2.WebUI/Default.aspx", vc, clientCookie.viewState, clientCookie.cookie)(userName, password)
    clientCookie.loadCookie(submitLoginResult._1, submitLoginResult._2)

    // 查看登录结果
    val loginStatus = this.checkLoginStatus("http://app02.szaic.gov.cn/WERMIS2.WebUI/MainPage.aspx", clientCookie.cookie)

    // 返回
    return if(loginStatus) clientCookie else null
  }

  def main(str : Array[String]) = {
    var flag = false
    var cookie : ClientParams = null
    for(count <- 1 to 10; if(!flag)) {
      println(count)
      try {
        cookie = this.login("zhangxin163", "8624608")
        flag = if(cookie == null) false else true
      }catch {
        case e : Exception => println(e);new RuntimeException(e)
      }

    }
    if(flag)
      println("登录成功")
    else
      println("登录10次后，失败")

  }
}
